// 处方综合管理
import React, { useState, useEffect } from "react";
import { Table, Button, Modal, Image, Input, Pagination, message } from "antd";
import {
  EditTwoTone,
  DeleteTwoTone,
  SearchOutlined,
  ContainerTwoTone,
} from "@ant-design/icons";
import {
  fetchRecipelDetail,
  fetchRecipelList,
  fetchRecipelAdd,
  fetchRecipelDelete,
  fetchRecipelAllDel,
} from "../../../request/hytApi";

import { format } from "date-fns";

const PrescriptionManagement = () => {
  const [visible, setVisible] = useState(false); // 控制 Modal 的显示
  const [currentRecord, setCurrentRecord] = useState(null); // 当前需要删除的记录
  const [dataSource, setDataSource] = useState([]); // 初始化数据源
  const [nameFilter, setNameFilter] = useState(""); // 名字过滤
  const [addressFilter, setAddressFilter] = useState(""); // 地址过滤
  const [current, setCurrent] = useState(1); // 当前页
  const [pageSize, setPageSize] = useState(5); // 每页显示的条数
  const [editingItem, setEditingItem] = useState(null); // 存储正在编辑的行数据
  const [delItem, setdelItem] = useState([]); // 删除的id数据
  const [totalPrice, setTotalPrice] = useState(0); // 初始化总价
  const [isModalVisible, setIsModalVisible] = useState(false); //详情对话框开关
  const [modalData, setModalData] = useState([]); //详情数据

  useEffect(() => {
    const sum = modalData.reduce((sum, item) => {
      return sum + item.price * item.count;
    }, 0);
    setTotalPrice(sum);
    console.log("🚀 ~ sum ~ sum:", sum);
  }, [modalData]); // 只有 dataSource 变化时会执行

  // .请求药品数据
  useEffect(() => {
    fetchRecipelListFn();
  }, []);

  // .请求药品数据
  const fetchRecipelListFn = async () => {
    const res = await fetchRecipelList({
      page: 1,
      size: 100,
    });
    console.log(res);
    setDataSource(res.data);
  };

  // .处理输入框的变化
  const handleNameChange = (e) => {
    setNameFilter(e.target.value);
  };

  const handleAddressChange = (e) => {
    setAddressFilter(e.target.value);
  };

  const handleChangePage = (page, pageSize) => {
    setCurrent(page);
    setPageSize(pageSize);
    // 在这里可以处理数据的更新，通常你会做 API 请求获取当前页的数据
  };

  // .删除请求
  const fetchRecipelDeleteFn = async (id) => {
    const res = await fetchRecipelDelete({
      id: id,
    });
    if (res.code === 1) {
      fetchRecipelListFn();
      // 关闭对话框
      message.success("删除成功");
    } else {
      message.error("删除失败");
    }
  };

  // .处理删除
  const handleDelete = async (key) => {
    setVisible(true);
    setCurrentRecord(key); // 保存当前要删除的记录
  };

  // .确认删除
  const confirmDelete = async () => {
    // 在这里执行删除操作
    console.log("删除记录，数据:", currentRecord);
    fetchRecipelDeleteFn(currentRecord);
    setVisible(false);
  };

  // .取消删除
  const cancelDelete = () => {
    setVisible(false); // 关闭对话框
    setCurrentRecord(null); // 清空当前记录
  };

  //.复选框事件
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      // selectedRowKeys 是勾选的行的 key
      // selectedRows 是勾选的行的完整数据
      console.log("Selected Row Keys: ", selectedRows);
      // 获取 selectedRows 中每一项的 id
      const selectedIds = selectedRows.map((row) => row.id); // 假设每一行有 id 字段
      setdelItem(selectedIds);
      // 使用展开运算符将 selectedIds 合并到 delItem 中
    },
  };

  // .处理批量删除
  const handleAllDel = async () => {
    const str = JSON.stringify(delItem);
    console.log("🚀 ~批量删除id:", str);
    const res = await fetchRecipelAllDel({
      ids: str,
    });

    if (res.code === 1) {
      fetchRecipelListFn();
      message.success("删除成功");
    } else {
      message.error("删除失败");
    }
  };

  // ?详情
  const handleDetail = async (key) => {
    console.log("详情", key);

    const res = await fetchRecipelDetail({
      id: key,
    });
    console.log("🚀 ~ res:", res.data[0].price);

    let correctedJsonString = res.data[0].recipel.replace(/'/g, '"');
    console.log(
      "🚀 ~ handleDetail ~ correctedJsonString:",
      correctedJsonString
    );
    const correctedJsonArr = JSON.parse(correctedJsonString);
    console.log("🚀 ~ handleDetail ~ arr:", correctedJsonArr[0]);
    // 这里可以根据 id 获取相关数据，当前用模拟数据代替
    setModalData(correctedJsonArr); // 模拟设置数据
    setIsModalVisible(true); // 显示对话框
  };

  // 关闭对话框的处理函数
  const handleCloseModal = () => {
    setIsModalVisible(false); // 隐藏对话框
  };

  // .查询按钮点击事件
  const handleSearch = async () => {
    if (nameFilter || addressFilter) {
      const filteredData = dataSource.filter(
        (item) =>
          item.name.includes(nameFilter) && // 根据 name 进行模糊匹配
          item.department.includes(addressFilter) // 根据 department 进行模糊匹配
      );

      setDataSource(filteredData); // 更新显示的数据
      message.success("查询成功");
    } else {
      fetchRecipelListFn();
    }
  };

  // .列定义
  const columns = [
    {
      title: "医生头像",
      dataIndex: "head",
      key: "id",
      render: (image) => (
        <Image
          width={50}
          height={50}
          src={image}
          style={{ borderRadius: "10px" }}
        />
      ),
    },
    {
      title: "医生名称",
      dataIndex: "name",
      key: "id",
      render: (text) => text,
    },
    {
      title: "处方开具科室",
      dataIndex: "department",
      key: "id",
      render: (text) => text,
    },
    {
      title: "处方金额  ",
      dataIndex: "price",
      key: "id",
      render: (text) => text,
    },

    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <div>
          {
            <>
              <Button
                type="link"
                icon={<ContainerTwoTone />}
                onClick={() => handleDetail(record.id)} // 点击编辑按钮时调用 handleEdit
              />

              <Button
                type="link"
                onClick={() => handleDelete(record.id)}
                danger
                icon={<DeleteTwoTone />}
              />
            </>
          }
        </div>
      ),
    },
  ];

  // .表格列的配置
  const detailColumns = [
    {
      title: "药品名称",
      dataIndex: "drugsname",
      key: "drugsname",
    },
    {
      title: "药品图片",
      dataIndex: "img",
      key: "img",
      render: (text) => (
        <img src={text} alt="药品图片" style={{ width: 50, height: 50 }} />
      ),
    },
    {
      title: "药品规格",
      dataIndex: "type",
      key: "type",
    },
    {
      title: "药品单价",
      dataIndex: "price",
      key: "price",
      render: (text) => `¥${text.toFixed(2)}`,
    },
    {
      title: "药品数量",
      dataIndex: "count",
      key: "count",
    },
    {
      title: "有效期",
      dataIndex: "endtime",
      key: "endtime",
    },
    {
      title: "用药备注",
      dataIndex: "other",
      key: "other",
    },
  ];

  return (
    <div>
      {/* 输入框和查询按钮 */}
      <div
        style={{ marginBottom: "15px", display: "flex", alignItems: "center" }}
      >
        <span style={{ marginRight: "10px", marginLeft: "10px" }}>
          医生名称
        </span>
        <Input
          placeholder="请输入医生名称"
          style={{ width: 250, marginRight: 10 }}
          value={nameFilter}
          onChange={handleNameChange} // 绑定输入框的变化
        />
        <span style={{ marginRight: "10px" }}>处方开具科室</span>

        <Input
          placeholder="请输入处方科室"
          style={{ width: 250, marginRight: 10 }}
          value={addressFilter}
          onChange={handleAddressChange} // 绑定输入框的变化
        />
        <Button
          style={{ marginRight: "auto" }}
          type="primary"
          onClick={handleSearch}
          icon={<SearchOutlined />}
        >
          查询
        </Button>

        <Button onClick={handleAllDel}>删除选中</Button>
      </div>
      {/* 表格 */}
      <Table
        style={{ marginBottom: "10px" }}
        rowSelection={rowSelection} // 配置复选框
        rowKey="id" // 设置行 key
        columns={columns}
        dataSource={dataSource.slice(
          (current - 1) * pageSize,
          current * pageSize
        )} // 分页数据
        pagination={false} // 禁用默认分页器
      />
      {/* 自定义分页器放置在左侧 */}
      <div style={{ marginBottom: "16px", textAlign: "left" }}>
        <Pagination
          style={{ marginLeft: "10px" }}
          current={current}
          pageSize={pageSize}
          total={dataSource.length} // 数据的总数
          onChange={handleChangePage}
          showSizeChanger
          pageSizeOptions={["5", "10", "20", "50"]}
          showTotal={(total) => `共 ${total} 条数据`}
        />
      </div>
      {/* 删除确认对话框 */}

      <Modal
        width={600}
        title="系统提示"
        open={visible}
        onOk={confirmDelete} // 点击确认时执行删除
        onCancel={cancelDelete} // 点击取消时关闭对话框
        okText="确定"
        cancelText="取消"
      >
        <p>
          您正在删除用户挂号信息，此操作不可逆，删除后患者需重新挂号，确定删除吗？
        </p>
      </Modal>

      {/* 详情对话框 */}
      {/* 对话框 */}
      <Modal
        title="药品详情"
        visible={isModalVisible}
        footer={null} // 关闭footer
        onCancel={handleCloseModal} // 点击叉号时关闭对话框
        closeIcon={<span style={{ fontSize: 16 }}>×</span>} // 自定义叉号样式
        width={800} // 可以调整对话框的宽度
      >
        <Table
          columns={detailColumns}
          dataSource={modalData}
          pagination={false} // 禁用分页
          rowKey="key" // 设置表格行的唯一标识
        />
        {/* // const [modalPrice, setModalPrice] = useState(""); */}

        <div style={{ marginTop: "10px", width: "100%", textAlign: "right" }}>
          总价：{totalPrice}
        </div>
      </Modal>
    </div>
  );
};

export default PrescriptionManagement;
